package com.sxz.sbs.module.update;


import android.Manifest;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sxz.sbs.R;
import com.sxz.sbs.entity.UploadAppBean;
import com.vector.update_app.view.NumberProgressBar;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import static android.content.Context.DOWNLOAD_SERVICE;

/**
 * 在线更新
 */
public class UploadAppFragment extends DialogFragment {
    public static final String TIPS = "请授权访问存储空间权限，否则App无法更新";
    public static boolean isShow = false;
    private TextView mContentTextView;
    private Button mUpdateOkButton;
    private NumberProgressBar mNumberProgressBar;
    private ImageView mIvClose;
    private TextView mTitleTextView;
    private LinearLayout mLlClose;
    private ImageView mTopIv;
    private TextView mIgnore;
    public static final String UPDATE_BEAN = "update_bean";
    public static UploadAppFragment newInstance(UploadAppBean bean) {
        Bundle args = new Bundle();
        UploadAppFragment fragment = new UploadAppFragment();
        args.putParcelable(UPDATE_BEAN,bean);
        fragment.setArguments(args);
        return fragment;
    }
    private UploadAppBean bean;
    private DownloadManager downloadManager;
    private DownloadManager.Request request;
    private Timer timer;
    private long id = -1;
    private TimerTask task;
    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            int pro = bundle.getInt("pro");
            String name  = bundle.getString("name");
            mNumberProgressBar.setProgress(pro);
        }
    };
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyDialog);
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.fragment_upload_app, null);
        initView(view);
        builder.setView(view);
        Dialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }

    private void initView(View view) {
        //提示内容
        mContentTextView = (TextView) view.findViewById(R.id.tv_update_info);
        //标题
        mTitleTextView = (TextView) view.findViewById(R.id.tv_title);
        //更新按钮
        mUpdateOkButton = (Button) view.findViewById(R.id.btn_ok);
        //进度条
        mNumberProgressBar = (NumberProgressBar) view.findViewById(R.id.npb);
        //关闭按钮
        mIvClose = (ImageView) view.findViewById(R.id.iv_close);
        //关闭按钮+线 的整个布局
        mLlClose = (LinearLayout) view.findViewById(R.id.ll_close);
        //顶部图片
        mTopIv = (ImageView) view.findViewById(R.id.iv_top);
        //忽略
        mIgnore = (TextView) view.findViewById(R.id.tv_ignore);
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        bean = getArguments().getParcelable(UPDATE_BEAN);
        if (bean != null) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("新版本大小：" + bean.getSize() + "\n\n");
            stringBuilder.append(bean.getContent());
            mContentTextView.setText(stringBuilder.toString());
            //标题
            mTitleTextView.setText(String.format("是否升级到%s版本？", bean.getVersion()));
            //强制更新
            if (bean.getIsForce() == 1) {
                setCancelable(false);
                mLlClose.setVisibility(View.GONE);
            }
            initDownLoad(bean);
        }
        mUpdateOkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermission();
            }
        });
        mIvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    private void initDownLoad(UploadAppBean bean) {
        downloadManager = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
        request = new DownloadManager.Request(Uri.parse(bean.getURL()));
        request.setTitle("百年利人");
        if (NetworkUtils.isWifiConnected()) {
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        } else {
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
        }
        request.setAllowedOverRoaming(false);
        request.setMimeType("application/vnd.android.package-archive");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //创建目录
        final String apkName = System.currentTimeMillis()+"";
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir() ;
        //设置文件存放路径
        request.setDestinationInExternalFilesDir( getActivity(),Environment.getDataDirectory().getAbsolutePath() , apkName+".apk" ) ;
        mNumberProgressBar.setMax(100);
        final  DownloadManager.Query query = new DownloadManager.Query();
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                Cursor cursor = downloadManager.query(query.setFilterById(id));
                if (cursor != null && cursor.moveToFirst()) {
                    if (cursor.getInt(
                            cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                        //mNumberProgressBar.setProgress(100);
                        install(Environment.getDataDirectory().getAbsolutePath() + "/"+apkName+".apk" );
                        task.cancel();
                    } else if (cursor.getInt(
                            cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_FAILED) {
                        ToastUtils.showShort("下载失败");
                        dismiss();
                        task.cancel();
                    }
                    String title = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE));
                    String address = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                    int pro =  (bytes_downloaded * 100) / bytes_total;
                    Message msg = Message.obtain();
                    Bundle bundle = new Bundle();
                    bundle.putInt("pro",pro);
                    bundle.putString("name",title);
                    msg.setData(bundle);
                    handler.sendMessage(msg);
                }
                cursor.close();
            }
        };
        timer.schedule(task, 0,1000);
    }

    private void install(String s) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = (new File(s));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            Uri apkUri = FileProvider.getUriForFile(getActivity(), "com.sxz.sbs.provider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            Uri data = Uri.fromFile(file);
            intent.setDataAndType(data,"application/vnd.android.package-archive");
        }
        String[] command = {"chmod", "777", file.getPath() };
        ProcessBuilder builder = new ProcessBuilder(command);
        try {
            builder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (getActivity().getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            getActivity().startActivityForResult(intent,666);
        }

    }

    private void requestPermission() {
        /*PermissionUtils.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.REQUEST_INSTALL_PACKAGES,
                Manifest.permission.READ_EXTERNAL_STORAGE).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                downloadAPP();
            }

            @Override
            public void onDenied() {
                Toast.makeText(getActivity(), TIPS, Toast.LENGTH_LONG).show();
            }
        }).request();*/
        int flag = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int flag1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.REQUEST_INSTALL_PACKAGES);
        int flag2 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
        if (flag != PackageManager.PERMISSION_GRANTED && flag1 != PackageManager.PERMISSION_GRANTED
                && flag2 !=  PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // 用户拒绝过这个权限了，应该提示用户，为什么需要这个权限。
                Toast.makeText(getActivity(), TIPS, Toast.LENGTH_LONG).show();
            } else {
                // 申请授权。
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE
                        ,Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.REQUEST_INSTALL_PACKAGES}, 1);
            }
        } else {
            downloadAPP();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                downloadAPP();

            } else {
                //提示，并且关闭
                Toast.makeText(getActivity(), TIPS, Toast.LENGTH_LONG).show();
                dismiss();

            }
        }
    }

    /**
     * 下载app
     */
    private void downloadAPP() {
        if (!canDownloadState(getActivity())) {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(bean.getURL());
            intent.setData(content_url);
            getActivity().startActivity(intent);
            return;
        }
        id = downloadManager.enqueue(request);
        task.run();
        mUpdateOkButton.setVisibility(View.GONE);
        mNumberProgressBar.setVisibility(View.VISIBLE);
        if (bean.getIsForce() != 1) {
            setCancelable(false);
            mLlClose.setVisibility(View.GONE);
        }
    }

    /**
     * 弹窗
     * @param fragmentManager
     */
    public void showDialog(FragmentManager fragmentManager) {
        this.show(fragmentManager, "Dialog");
    }
    private  boolean canDownloadState(Context ctx) {
                try {
                      int state = ctx.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
                      if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                              || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                               || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                               return false;
                         }
                  } catch (Exception e) {
                       e.printStackTrace();
                       return false;
                   }
                 return true;
             }

}
